import { globSync, sync } from "glob";
import { resolveApp } from "./path";
import { existsSync } from "fs";
import HtmlWebpackPlugin from "html-webpack-plugin";
import fs from "fs-extra";
import dotEnv from "dotenv";
import dotEnvExpand from "dotenv-expand";

export const loadEnv = () => {
  const pathsDotEnv = resolveApp(".env");
  const modeVal = process.env.mode;
  const envConfig = dotEnv.config({
    path: `${pathsDotEnv}.${modeVal}`,
  });

  dotEnvExpand.expand(envConfig);
};

export const getEntry = () => {
  const files = globSync("./src/pages/**/*.view.{ts,js,jsx,tsx}");
  const entry: Record<string, string> = {};
  const isWin = process.platform === "win32";

  files.forEach((file: string) => {
    if (isWin && file) {
      file = file.replaceAll("\\", "/");
    }
    const ret = file.match(/^src\/pages\/(\S*)\.view\.(js|ts|jsx|tsx)$/);
    if (ret) {
      const name = ret[1];
      const path = resolveApp(ret[0]);
      if (existsSync(path)) {
        entry[`${name}.view`] = path;
      }
    }
  });

  return entry;
};

// const entry = getEntry();
// console.log(entry);

function getHtmlConfig(name: string, path: string): HtmlWebpackPlugin.Options {
  return {
    chunks: [`${name}`],
    template: path.replace(/\.(js|ts|jsx|tsx)$/, ".html"),
    filename: `${name}.html`,
    //  favicon: './static/logo.png', //该配置回导致在html同级目录下多出一个logo.png文件
    hash: true,
    inject: "body",
  };
}

/**
 * @cooper
 * @description 根据getEntry返回的入口配置对象分别创建HtmlWebpackPlugin
 * @param {Object} | entries
 * @returns {Array}
 */
export function createHtmlWebpackPlugin(
  entries: Record<string, string>,
): HtmlWebpackPlugin.Options[] {
  const pluginArr = [];
  for (const key in entries) {
    if (entries.hasOwnProperty(key)) {
      const path = entries[key];
      const configOptions = getHtmlConfig(key, path);
      pluginArr.push(new HtmlWebpackPlugin(configOptions));
    }
  }
  return pluginArr;
}

export function getProjectName(): string {
  const jsonStr = fs.readFileSync("./package.json", "utf8").toString();
  const { name } = JSON.parse(jsonStr);
  return name;
}

// getProjectName();
